package com.crm.system.service.impl.productManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.constant.ProjectBusinessConstant;
import com.crm.common.exception.FastDFSException;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.QRCodeUtil;
import com.crm.common.util.RedisUtil;
import com.crm.model.entity.contractReviewManager.ContractReview;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.sys.FileUpload;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.productManager.CustomerMemberProductAddQO;
import com.crm.model.qo.productManager.CustomerMemberProductEditQO;
import com.crm.model.vo.productManager.*;
import com.crm.model.qo.productManager.ProductQRCodeQO;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.system.service.FileUploadService;
import com.crm.system.service.productManager.CustomerMemberProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.List;

/**
 * @author yincuimei
 * @Date 2021/4/12 16:24
 */
@Service
@Slf4j
public class CustomerMemberProductServiceImpl implements CustomerMemberProductService {
    @Autowired
    private CustomerMemberProductDbService memberProductDbService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    FileUploadService fileUploadService;

    /**
     * 产品管理--会员产品列表分页信息
     * @param productStatus        ---产品停、启用状态
     * @param memberCardName       ---会员卡名称
     * @param sysType              ---系统类型(用户-user/管理-management)
     * @param pageIndex/ pageSize  ---页码、分页大小
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<CustomerMemberProductVO> selectCustomerMemberProductVOList(String productStatus,Integer pageIndex,Integer pageSize,String sortName,String sortOrder,String memberCardName,String sysType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){//点击会员卡名称列排序
            switch(sortName){
                case "memberCardName": {
                    order.append("member_card_name ").append(sortOrder);//会员卡名称
                }
                break;
                case "productPeriodValidity": {
                    order.append("product_period_validity_start ").append(sortOrder);//产品有效期开始日期
                }
                break;
                default:
                    break;
            }

        }else{//默认排序(先按是否启用排序，再按产品名称排序)
            order.append("product_status ").append("asc");//是否启用
            order.append(",member_card_name ").append("asc");//会员卡名称
        }
        List<CustomerMemberProduct> memberProductList = memberProductDbService.selectCustomerProductList(productStatus,memberCardName,sysType,order.toString());
        PageInfo<CustomerMemberProduct> pageInfo = new PageInfo<>(memberProductList);
        List<CustomerMemberProductVO> memberProductVOList = new ArrayList<CustomerMemberProductVO>();
        pageInfo.getList().stream().forEach(customerMemberProduct -> {
            CustomerMemberProductVO customerMemberProductVO = new CustomerMemberProductVO();
            BeanUtils.copyProperties(customerMemberProduct, customerMemberProductVO);
            memberProductVOList.add(customerMemberProductVO);
        });
        return new DhPageInfo<CustomerMemberProductVO>(pageInfo, memberProductVOList);
    }

    /**
     * 产品管理--新增会员产品
     * @param memberProductAddQO  ---会员产品信息
     * @param multipartFile
     * @author yincuimei
     * @return
     */
    @Override
    public JSONObject insertCustomerMemberProduct(CustomerMemberProductAddQO memberProductAddQO, MultipartFile multipartFile) throws FastDFSException {
        JSONObject json = new JSONObject();
        Boolean result;
        if(memberProductAddQO != null){
            //1:校验会员卡名称是否重复(chs_customer_member_product)
            result = memberProductDbService.isExistMemberCardName(memberProductAddQO.getMemberCardName(),(short)StatusCodeEnum.NORMAL_CODE.getState());
            if(result){
                json.put("memberCardNameRepeat",true);//会员卡名称重复
                return json;
            }
            //2:校验会员产品编码是否重复(chs_customer_member_product)
            result = memberProductDbService.isExistMemberProductCode(memberProductAddQO.getMemberProductCode(),(short)StatusCodeEnum.NORMAL_CODE.getState());
            if(result){
                json.put("memberProductCodeRepeat",true);//会员产品编码重复
                return json;
            }
            //3.添加会员产品(chs_customer_member_product)
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
            FileUpload fileUpload = fileUploadService.uploadFile(multipartFile, false);
            CustomerMemberProduct customerMemberProduct = new CustomerMemberProduct();
            customerMemberProduct.setMemberProductId(CommonUtils.getGUID());//主键
            customerMemberProduct.setMemberCardName(memberProductAddQO.getMemberCardName());//会员卡名称
            customerMemberProduct.setMemberProductCode(memberProductAddQO.getMemberProductCode());//产品编码
            customerMemberProduct.setSellingCardPrice(memberProductAddQO.getSellingCardPrice());//售卡价格
            customerMemberProduct.setServiceNumber(memberProductAddQO.getServiceNumber()); //会员服务总次数
            customerMemberProduct.setProductMembershipLevel(memberProductAddQO.getMembershipLevel()); //会员等级
            customerMemberProduct.setMemberCardImg(fileUpload != null ? fileUpload.getUploadId() : "");//会员图片
            customerMemberProduct.setProductPeriodValidityStart(memberProductAddQO.getProductPeriodValidityStart());//产品有效期起始日期
            customerMemberProduct.setProductPeriodValidityEnd(memberProductAddQO.getProductPeriodValidityEnd());//产品有效期截止日期
            customerMemberProduct.setWhetherIncludedAchievement(memberProductAddQO.getWhetherIncludedAchievement());//是否计入会员产品业绩
            customerMemberProduct.setWhetherRenew(memberProductAddQO.getWhetherRenew());//是否可续费(7-30加的)
            customerMemberProduct.setDeleteStatus((short)StatusCodeEnum.NORMAL_CODE.getState());//删除状态
            customerMemberProduct.setPerformanceConversionRatio(memberProductAddQO.getPerformanceConversionRatio());//业绩换算比例
            customerMemberProduct.setCreatePeopleId(userAccount.getAccountId());//创建人ID
            customerMemberProduct.setCreateTm(new Date());//创建时间
            customerMemberProduct.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
            customerMemberProduct.setUpdateTm(new Date());//更新时间
            customerMemberProduct.setProductStatus("0");//停、启用状态--0:启用;1:停用
            memberProductDbService.insertCustomerMemberProduct(customerMemberProduct);
            json.put("addCustomerMemberProduct",true);//会员产品添加成功
        }
        return json;
    }

    /**
     * 会员产品列表--会员卡产品停、启用操作
     * @param memberProductId  ---主键
     * @param productStatus    ---产品停/启用状态--0:启用;1:停用
     * @return
     * @author yincuimei
     */
    @Override
    public Boolean updateProductStatusById(String memberProductId,String productStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        CustomerMemberProduct memberProduct = new CustomerMemberProduct();
        memberProduct.setMemberProductId(memberProductId);//主键
        memberProduct.setProductStatus(productStatus);//产品状态(停、启用)
        memberProduct.setUpdateTm(new Date());//更新时间
        memberProduct.setUpdatePeopleId(userAccount.getAccountId());
        return memberProductDbService.updateProductStatusById(memberProduct);
    }

    /**
     * 根据产品id查询产品详情
     * @param memberProductId
     * @return
     */
    @Override
    public List<CustomerProductDetailVO> queryCustomerProductDetailInfo(String memberProductId) {

        List<CustomerProductDetailVO> customerProductDetailList = memberProductDbService.queryCustomerProductDetailInfo(memberProductId);

        return customerProductDetailList;
    }

    /**
     * 生成产品二维码
     * @param createQRCodeReq
     * @return
     */
    @Override
    public String createDRCode(ProductQRCodeQO createQRCodeReq) {
        //生成token
        String tokenStr = UUID.randomUUID().toString();
        //判断根据所传的token有效时长存入redis
        if("0".equals(createQRCodeReq.getTokenTime())){
            //永久有效，根据当前时间戳生成token
            redisUtil.setIfAbsent("token",tokenStr);
        }else{
            redisUtil.setEx("token",tokenStr,Long.valueOf(createQRCodeReq.getTokenTime()), TimeUnit.DAYS);
        }
        //将生成二维码的第三个参数设置为随机生成的token
        createQRCodeReq.setTokenTime(tokenStr);
        String contents = new Gson().toJson(createQRCodeReq);
        //TODO 设置临时链接
        String link = "http://www.baidu.com";
        String base64 = QRCodeUtil.creatRrCode(link, 180, 180);
        return base64;
    }


    /**
     * 根据产品id修改产品销售价格
     * @param memberEditQO
     * @return
     */
    @Override
    public boolean updateCardPrice(CustomerMemberProductEditQO memberEditQO) {
        return memberProductDbService.updateCardPrice(memberEditQO);
    }

    /**
     * 根据token跳转链接
     * @param token
     * @return
     */
    @Override
    public String copyLink(String token) {
        log.info("复制产品链接方法，接收到的token是【{}】",token);
        boolean exist = redisUtil.hasKey(token);
        if(exist){
            log.info("token存在！");
            String url = "http://www.baidu.com";
            return url;
        }
        return null;
    }

    /***
     * @Description: 查询合同添加的会员产品
     * @Param: pageIndex/pageSize 页码/每页显示个数
     * @Author: luojie
     * @Date: 2021/4/19 14:11
     */
    @Override
    public DhPageInfo<ContractMemberProductVO> selectContractMemberProductList(Integer pageIndex, Integer pageSize,String productName,String whetherRenew) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<ContractMemberProductVO> contractMemberProductVOList = new ArrayList<>();
        List<CustomerMemberProduct> memberProductList = memberProductDbService.selectContractMemberProductList(productName,whetherRenew,"");
        PageInfo<CustomerMemberProduct> pageInfo = new PageInfo<CustomerMemberProduct>(memberProductList);
        pageInfo.getList().stream().forEach(customerMemberProduct -> {
            ContractMemberProductVO customerMemberProductVO = new ContractMemberProductVO();
            customerMemberProductVO.setCustomerProductId(customerMemberProduct.getMemberProductId());
            customerMemberProductVO.setProductCode(customerMemberProduct.getMemberProductCode());
            customerMemberProductVO.setProductName(customerMemberProduct.getMemberCardName());
            customerMemberProductVO.setProductMemberPrice(customerMemberProduct.getSellingCardPrice());
            customerMemberProductVO.setProductCategories("1");
            contractMemberProductVOList.add(customerMemberProductVO);
        });

        return new DhPageInfo<ContractMemberProductVO>(pageInfo, contractMemberProductVOList);
    }

    /**
     * 新增商机--会员产品列表
     * @return
     * @author baijian
     */
    @Override
    public DhPageInfo<CustomerMemberProductVO> selectSjCustomerMemberProductVOList(String productStatus, Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String memberCardName,String tag) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){//点击会员卡名称列排序
            switch(sortName){
                case "memberCardName": {
                    order.append("member_card_name ").append(sortOrder);//会员卡名称
                }
                break;
                case "sellingCardPrice": {
                    order.append("selling_card_price ").append(sortOrder);//售卡价格
                }
                break;
                default:
                    break;
            }
        }else{//默认排序(先按是否启用排序，再按产品名称排序)
            order.append("product_status ").append("asc");//是否启用
            order.append(",member_card_name ").append("asc");//会员卡名称
        }
        List<CustomerMemberProduct> memberProductList = memberProductDbService.selectSjCustomerMemberProductVOList(productStatus,memberCardName,order.toString(),tag);
        PageInfo<CustomerMemberProduct> pageInfo = new PageInfo<>(memberProductList);
        List<CustomerMemberProductVO> memberProductVOList = new ArrayList<CustomerMemberProductVO>();
        pageInfo.getList().stream().forEach(customerMemberProduct -> {
            CustomerMemberProductVO customerMemberProductVO = new CustomerMemberProductVO();
            BeanUtils.copyProperties(customerMemberProduct, customerMemberProductVO);
            memberProductVOList.add(customerMemberProductVO);
        });
        return new DhPageInfo<CustomerMemberProductVO>(pageInfo, memberProductVOList);
    }

    /**
     * 查询所有【启用状态】的会员卡名称
     * @author yincuimei
     * @return
     */
    @Override
    public List<String> selectMemberCardNameByProductStatus() {
        return memberProductDbService.selectMemberCardNameByProductStatus();
    }
}
